package com.ncmmall.mall.controller.securitys.shiro;

import com.feijin.commons.lang.Requires;
import com.ncmmall.domain.security.user.WebUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import javax.servlet.http.HttpServletRequest;

/**
 * @author tongchun
 *         通用安全工具类
 */
public final class Securitys {

    private Securitys() {
    }

    private static final String CURRENT_USER = "CURRENT_USER";

    /**
     * 激活shiro会话
     *
     * @param user
     */
    public static void activateUserSession(WebUser user) {
        Requires.notNull(user, "user must not be null.");
        Subject subject = SecurityUtils.getSubject();
        subject.getSession().setAttribute(CURRENT_USER, user);
    }

    /**
     * 获取session
     *
     * @return
     */
    public static Session getSession() {
        Subject subject = SecurityUtils.getSubject();
        return subject.getSession();
    }

    /**
     * 获取当前登录的用户
     *
     * @return
     */
    public static WebUser currentUser() {
        Subject subject = SecurityUtils.getSubject();
        return (WebUser) subject.getSession().getAttribute(CURRENT_USER);
    }

    /**
     * 解除session
     */
    public static void unactivateUserSession() {
        Subject subject = SecurityUtils.getSubject();
        subject.getSession().setAttribute(CURRENT_USER, null);
    }

    /**
     * 获取IP地址
     *
     * @param request
     * @return
     */
    public static String getIp(HttpServletRequest request) {
        return request.getHeader("x-forwarded-for");
    }


}
